﻿using System;
using DL.Tools;
using UnityEngine;

namespace DL.AI.AIGOAP
{
    //传感器
    [RequireComponent(typeof(SphereCollider))]
    public class Sensor : MonoBehaviour
    {
        [SerializeField] private float m_DetectionRadius = 5f;
        [SerializeField] private float m_TimerInterval = 1f;

        private SphereCollider m_DetectionRange;

        public event Action OnTargetChanged;

        private GameObject m_Target;
        private Vector3 m_LastKnownPosition;
        private GameTimer m_GameTimer;

        public Vector3 TargetPosition => m_Target ? m_Target.transform.position : Vector3.zero;
        public bool IsTargetInRange => TargetPosition != Vector3.zero;

        private void Awake()
        {
            m_DetectionRange = GetComponent<SphereCollider>();
            m_DetectionRange.isTrigger = true;
            m_DetectionRange.radius = m_DetectionRadius;
        }


        private void Start()
        {
            m_GameTimer = NewTimerManager.Inst.GetTimer(m_TimerInterval, TimerOver);
        }

        private void TimerOver()
        {
            UpdateTargetPosition(m_Target);
            m_GameTimer = NewTimerManager.Inst.GetTimer(m_TimerInterval, TimerOver);
        }

        private void UpdateTargetPosition(GameObject target = null)
        {
            m_Target = target;
            if (IsTargetInRange && (m_LastKnownPosition != TargetPosition || m_LastKnownPosition != Vector3.zero))
            {
                m_LastKnownPosition = TargetPosition;
                OnTargetChanged?.Invoke();
            }
        }

        private void OnTriggerEnter(Collider other)
        {
            if(!other.CompareTag("Player")) return;
            UpdateTargetPosition(other.gameObject);
        }

        private void OnTriggerExit(Collider other)
        {
            if(!other.CompareTag("Player")) return;
            UpdateTargetPosition();
        }

        private void OnDrawGizmos()
        {
            Gizmos.color = IsTargetInRange ? Color.red : Color.green;
            Gizmos.DrawWireSphere(transform.position, m_DetectionRadius);
        }
    }
}